package com.smartwork.common.mobile.wechat.thread;

import com.smartwork.common.mobile.wechat.bean.JsapiTicket;
import com.smartwork.common.mobile.wechat.util.WeixinConfUtils;
import com.smartwork.common.mobile.wechat.util.WeixinUtil;
import com.smartwork.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;


/** 
 * 定时获取微信access_token的线程 
 *  
 * @author liuyq 
 * @date 2013-05-02 
 */  
public class JsapiTicketThread implements Runnable {  
    private static Logger log = LoggerFactory.getLogger(JsapiTicketThread.class);
    
    private static JsapiTicket jsapiTicket = null;

    private static ConcurrentHashMap<String, JsapiTicket> jsapiTicketHashMap
                            = new ConcurrentHashMap<String, JsapiTicket>();

    private String groupId;

    public JsapiTicketThread(String groupId) {
        this.groupId = groupId;
    }

    public void run() {  
        while (true) {  
            try {
            	if (null != TokenThread.getAccessTokenStr(groupId)) {
                	jsapiTicket = WeixinUtil.getJsapiTicket(TokenThread.getAccessTokenStr(groupId));

                    if (null != jsapiTicket) {
                        jsapiTicketHashMap.put(groupId, jsapiTicket);
                        WeixinConfUtils.setValue(groupId, "jsapiTicket", jsapiTicket.getTicket());
                        // 休眠7000秒
                        Thread.sleep((jsapiTicket.getExpiresIn() - 200) * 1000);  
                    } else {  
                        // 如果jsapiTicket为null，60秒后再获取  
                        Thread.sleep(60 * 1000);  
                    } 
            	} else {
                    // 如果AccessToken为null，60秒后再获取  
                    Thread.sleep(30 * 1000);
            	}
            } catch (InterruptedException e) {  
                try {  
                    Thread.sleep(60 * 1000);  
                } catch (InterruptedException e1) {  
                    log.error("{}", e1);  
                }  
                log.error("{}", e);  
            }  
        }  
    }

    public static synchronized String getJsapiTicketStr(String groupId) {
        if(jsapiTicketHashMap == null || jsapiTicketHashMap.size() == 0) {
            String ticket = WeixinConfUtils.getValue(groupId, "jsapiTicket");
            if (StringUtils.isEmpty(ticket)) {
                return null;
            } else {
                return ticket;
            }
        }
        return jsapiTicketHashMap.get(groupId).getTicket();
    }
}